#include "sdlqtrgb.h"
#include <SDL.h>
#pragma comment(lib,"SDL2.lib")
static SDL_Window* sdl_win = NULL;
static SDL_Renderer* sdl_render = NULL;
static SDL_Texture* sdl_texture = NULL;
static int sdl_width = 0;
static int sdl_height = 0;
static unsigned  char* rgb = NULL;
static int pix_size = 4;
void SdlQtRGB::timerEvent(QTimerEvent* ev)
{
    static unsigned char tmp = 255;
    tmp--;
    for (int j = 0; j < sdl_height; j++)
    {
        int b = j * sdl_width* pix_size;
        for (int i = 0; i < sdl_width * pix_size; i += pix_size)
        {
            rgb[b + i] = 0;         //B
            rgb[b + i + 1] = tmp;   //G
            rgb[b + i + 2] = 0;     //R
            rgb[b + i + 3] = 0;     //A
        }
    }
    SDL_Rect rect;
    rect.x = 0;
    rect.y = 0;
    rect.w = sdl_width*ui.label->devicePixelRatio();
    rect.h = sdl_height*ui.label->devicePixelRatio();
    SDL_UpdateTexture(sdl_texture, &rect, rgb, sdl_width * pix_size);
    SDL_RenderClear(sdl_render);
    SDL_RenderCopy(sdl_render,sdl_texture,&rect,&rect);
    SDL_RenderPresent(sdl_render);
}

SdlQtRGB::SdlQtRGB(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    // ??????????????
    show();
    QApplication::processEvents();
    
    sdl_width = ui.label->width();
    sdl_height = ui.label->height();
    
    SDL_Init(SDL_INIT_VIDEO);
    sdl_win = SDL_CreateWindowFrom((void*)ui.label->winId());
    sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED);
    
    // ???????label??
    if (sdl_texture) {
        SDL_DestroyTexture(sdl_texture);
    }
    
    sdl_texture = SDL_CreateTexture(sdl_render,
        SDL_PIXELFORMAT_ARGB8888,
        SDL_TEXTUREACCESS_STREAMING,
        sdl_width,
        sdl_height
    );
    
    if (rgb) {
        delete[] rgb;
    }
    rgb = new unsigned char[sdl_width * sdl_height * pix_size];
    memset(rgb, 0, sdl_width * sdl_height * pix_size);
    startTimer(10);
}

